<?php
/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2023-02-22
 * Time: 15:47:39
 * Info:
 */

namespace app\admin\controller;

use think\facade\View;
use libs\GetImgSrc;
use app\common\model\Category as CategoryModel;
use app\common\model\Content as ContentModel;
use app\common\model\ContentFlag as ContentFlagModel;
use app\common\model\ContentKeywords as ContentKeywordsModel;
use app\common\model\ModelsField as ModelsFieldModel;
use app\common\model\ContentExt as ContentExtModel;

class Content extends Base
{

    public function index()
    {
        if ($this->request->isAjax()) {
            $model_id = (int)input('model_id', 0);
            $limit    = (int)input('limit', 15);
            $page     = (int)input('page', 1);
            $key      = input('key');
            $first    = ($page - 1) * $limit;
            $where    = function ($query) use ($key, $model_id) {
                if ( ! empty($model_id)) {
                    $query->where('model_id', $model_id);
                }
                if ( ! empty($key['model_id'])) {
                    $query->where('model_id', $key['model_id']);
                }
                if ( ! empty($key['title'])) {
                    $query->whereLike('title', '%'.$key['title'].'%');
                }
                if ( ! empty($key['id'])) {
                    $query->where('id', $key['id']);
                }
                if ( ! empty($key['cate_id'])) {
                    $query->where('cate_id', $key['cate_id']);
                }
                if (isset($key['status']) && $key['status'] != '') {
                    $query->where('status', $key['status']);
                }
                if ( ! empty($key['flag'])) {
                    $query->where('id', 'IN', ContentFlagModel::where('flag_id', $key['flag'])->column('aid'));
                }
            };
            $count    = ContentModel::where($where)->count();
            $list     = ContentModel::field('id,cate_id,title,color,thumb,jump_url,click,sort,status,update_time')->with([
                'flag'     => function ($query) {
                    $query->where('status', 1)->field('aid,flag_id');
                },
                'category' => function ($query) {
                    $query->field('id,name');
                }
            ])->where($where)->limit($first, $limit)->order('update_time desc,id desc')->select()->toArray();
            foreach ($list as $key => $v) {
                $list[$key]['cate_name'] = $v['category']['name'] ?? '';
                $list[$key]['flag_name'] = '';
                $flagId                  = array_column($v['flag'], 'flag_id');
                if ( ! empty($flagId)) {
                    $list[$key]['flag_name'] = $this->flagName($flagId);
                }
            }
            $this->success('获取成功', $list, $count);
        }
        $model_id = (int)$this->request->get('model_id');
        $cates    = (new CategoryModel())->getPidCategoryList();
        $flags    = ContentFlagModel::FLAG;
        View::assign('cates', $cates);
        View::assign('flags', $flags);
        View::assign('model_id', $model_id);

        if ($model_id == 2) {
            $templage = "index_page";
        } else {
            $templage = "index";
        }

        return View::fetch($templage);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();

            if (empty($param['cate_id'])) {
                $this->error('请选择分类');
            }
            if (empty($param['title'])) {
                $this->error('标题不能为空');
            }
            if ( ! empty($param['flag']) && in_array(4, $param['flag']) && empty($param['jump_url'])) {
                $this->error('跳转url不能为空');
            }

            if (isset($param['auto_image']) && $param['auto_image'] == 1 && $param['thumb'] == '') {
                $param['thumb'] = GetImgSrc::src($param['content']) ?? "";
            }

            if ( ! empty($param['description'])) {
                $param['description'] = ! empty($param['description']) ? $param['description'] : mb_substr(strip_tags($param['content']),
                    0, 250, 'utf-8');
            }

            $param['publish_time'] = ! empty($param['publish_time']) ? strtotime($param['publish_time']) : time();
            $param['admin_id']     = cmf_get_admin_id();
            $param['create_time']  = time();
            $param['update_time']  = time();

            $extParamField = [];
            foreach ($param as $key => $value) {
                if (preg_match('/^ext_[\w\-]+$/', $key)) {
                    array_push($extParamField, $key);
                    unset($param[$key]);
                }
            }
            //判断特殊字段是否在提交的数组里面，并取出不在的
            $notInExtField = [];
            foreach ($extParamField as $e) {
                if ( ! empty($param['ext'])) {
                    if ( ! in_array($e, array_keys($param['ext']))) {
                        array_push($notInExtField, $e);
                    }
                }
            }
            //处理模型字段数据
            if ( ! empty($param['ext'])) {
                foreach ($param['ext'] as $key => $v) {
                    if (isset($param['ext'][$key]) && is_array($param['ext'][$key])) {
                        $param['ext'][$key] = implode(',', $param['ext'][$key]);
                    }
                    foreach ($notInExtField as $n) {
                        $param['ext'][$n] = '';
                    }
                }
            }

            try {
                $articleId = (new ContentModel)->strict(false)->insertGetId($param);
                if ( ! empty($param['ext'])) {
                    $param['ext']['content_id'] = $articleId;
                    //添加数据到模型字段表
                    (new ContentExtModel)->save($param['ext']);
                }
                //关联属性
                if ( ! empty($param['flag'])) {
                    (new ContentFlagModel())->articleFlagEdit($articleId, $param['flag']);
                }
                //关联关键字
                if (isset($param['keyword_names']) && $param['keyword_names']) {
                    (new ContentKeywordsModel)->articleKeywordsEdit($articleId, $param['keyword_names']);
                }
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('操作成功');
        }
        $model_id = (int)$this->request->get('model_id');
        $cates    = (new CategoryModel())->getPidCategoryList();
        $flags    = ContentFlagModel::FLAG;
        //模型字段
        $model_fields = $this->modelFields($model_id);

        View::assign('cates', $cates);
        View::assign('flags', $flags);
        View::assign('model_id', $model_id);
        View::assign('model_fields', $model_fields);

        return View::fetch();
    }

    public function edit()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            if (empty($param['id'])) {
                $this->error('参数错误');
            }
            if (empty($param['cate_id'])) {
                $this->error('请选择分类');
            }
            if (empty($param['title'])) {
                $this->error('标题不能为空');
            }
            if ( ! empty($param['flag']) && in_array(4, $param['flag']) && empty($param['jump_url'])) {
                $this->error('跳转url不能为空');
            }

            if (isset($param['auto_image']) && $param['auto_image'] == 1 && $param['thumb'] == '') {
                $param['thumb'] = GetImgSrc::src($param['content']) ?? "";
            }
            if ( ! empty($param['description'])) {
                $param['description'] = ! empty($param['description']) ? $param['description'] : mb_substr(strip_tags($param['content']),
                    0, 250, 'utf-8');
            }
            $param['publish_time'] = ! empty($param['publish_time']) ? strtotime($param['publish_time']) : time();
            $param['update_time']  = time();

            $extParamField = [];
            foreach ($param as $key => $value) {
                if (preg_match('/^ext_[\w\-]+$/', $key)) {
                    array_push($extParamField, $key);
                    unset($param[$key]);
                }
            }

            $param['ext']['content_id'] = $param['id'];

            //判断特殊字段是否在提交的数组里面，并取出不在的
            $notInExtField = [];
            foreach ($extParamField as $e) {
                if ( ! empty($param['ext'])) {
                    if ( ! in_array($e, array_keys($param['ext']))) {
                        array_push($notInExtField, $e);
                    }
                }
            }
            //处理模型字段数据
            if ( ! empty($param['ext'])) {
                foreach ($param['ext'] as $key => $v) {
                    if (isset($param['ext'][$key]) && is_array($param['ext'][$key])) {
                        $param['ext'][$key] = implode(',', $param['ext'][$key]);
                    }
                    foreach ($notInExtField as $n) {
                        $param['ext'][$n] = '';
                    }
                }
            }

            try {
                (new ContentModel)->strict(false)->update($param);
                //更新数据到模型字段表
                $findContentExt = ContentExtModel::where(['content_id' => $param['id']])->find();

                if ( ! empty($param['ext'])) {
                    if (empty($findContentExt)) {
                        //新增
                        (new ContentExtModel)->save($param['ext']);
                    } else {
                        //更新
                        $findContentExt->save($param['ext']);
                    }
                }

                $articleId = $param['id'];
                //关联属性
                if ( ! empty($param['flag'])) {
                    (new ContentFlagModel())->articleFlagEdit($articleId, $param['flag']);
                }
                //关联关键字
                if ( ! empty($param['keyword_names'])) {
                    (new ContentKeywordsModel)->articleKeywordsEdit($articleId, $param['keyword_names']);
                }
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }

            $this->success('操作成功');
        }
        $model_id = (int)$this->request->get('model_id');
        $id       = $this->request->param('id');
        if (empty($id)) {
            $this->error('参数错误');
        }
        $data = ContentModel::with([
            'flag'        => function ($query) {
                $query->where('status', 1)->field('aid,flag_id');
            },
            'content_ext' => function ($query) {
                $query->field('*');
            }
        ])->find($id);
        if (empty($data)) {
            $this->error('获取数据失败');
        }
        $data = is_object($data) ? $data->toArray() : $data;

        $data['flag_ids']     = array_column($data['flag'], 'flag_id');
        $data['publish_time'] = date('Y-m-d H:i:s', $data['publish_time']);

        $keyword_array = ContentKeywordsModel::alias('i')->leftJoin('keywords k', 'k.id = i.keywords_id')->where([
            'i.aid'    => $id,
            'k.status' => 1
        ])->order('i.create_time asc,i.keywords_id desc')->select()->toArray();

        $data['keyword_ids']   = implode(",", array_column($keyword_array, 'keywords_id'));
        $data['keyword_names'] = implode(',', array_column($keyword_array, 'title'));

        $cates = (new CategoryModel())->getPidCategoryList();
        $flags = ContentFlagModel::FLAG;
        //模型字段
        $model_fields = $this->modelFields($model_id, $data['content_ext']);

        View::assign('cates', $cates);
        View::assign('flags', $flags);
        View::assign('model_id', $model_id);
        View::assign('data', $data);
        View::assign('model_fields', $model_fields);
        //单页面
        if ($model_id == 2) {
            $template = 'edit_page';
        } else {
            $template = 'edit';
        }

        return View::fetch($template);
    }

    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = (int)input('get.id');
            if (empty($id)) {
                $this->error("参数错误");
            }
            ContentModel::destroy($id);
            $this->success('删除成功，请到回收站里查看');
        }
        $this->error('参数错误');
    }

    /**
     * 回收站列表
     * @return void
     */
    public function recycle()
    {
        if ($this->request->isAjax()) {
            $model_id = (int)input('model_id', 0);
            $limit    = (int)input('limit', 15);
            $page     = (int)input('page', 1);
            $key      = input('key');
            $first    = ($page - 1) * $limit;
            $where    = function ($query) use ($key, $model_id) {
                $query->where('model_id', $model_id);
                if ( ! empty($key['title'])) {
                    $query->whereLike('title', '%'.$key['title'].'%');
                }
                if ( ! empty($key['id'])) {
                    $query->where('id', $key['id']);
                }
                if ( ! empty($key['cate_id'])) {
                    $query->where('cate_id', $key['cate_id']);
                }
            };
            $count    = ContentModel::where($where)->onlyTrashed()->count();
            $list     = ContentModel::field('id,cate_id,title,color,thumb,jump_url,status,delete_time')->with([
                'category' => function ($query) {
                    $query->field('id,name');
                }
            ])->where($where)->limit($first, $limit)->order('delete_time desc')->onlyTrashed()->select()->toArray();
            foreach ($list as $key => $v) {
                $list[$key]['cate_name']   = $v['category']['name'] ?? '';
                $list[$key]['delete_time'] = date('Y-m-d h:i:s', $v['delete_time']);
            }
            $this->success('获取成功', $list, $count);
        }
        $model_id = (int)$this->request->get('model_id');
        $cates    = (new CategoryModel())->getPidCategoryList();
        View::assign('cates', $cates);
        View::assign('model_id', $model_id);

        return View::fetch();
    }

    /**
     * 回收站还原
     */
    public function recycleRollback()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id');
            if (empty($id)) {
                $this->error('参数错误');
            }
            $article = ContentModel::onlyTrashed()->find($id);
            $article->restore();
            $this->success('数据恢复成功');
        }
        $this->error('参数错误');
    }

    /**
     * 回收站彻底删除
     */
    public function recycleDel()
    {
        if ($this->request->isPost()) {
            $id = $this->request->param('id');
            if (empty($id)) {
                $this->error('参数错误');
            }
            ContentModel::destroy($id, true);
            //删除模型表（如果有）
            ContentExtModel::where('content_id', $id)->delete();
            //删除关联关键词表
            ContentKeywordsModel::where('aid', $id)->delete(true);
            //删除关联属性表
            ContentFlagModel::where('aid', $id)->delete(true);
            $this->success('数据已被永久删除');
        }
        $this->error('参数错误');
    }

    /*
    * flag 标签转换成字符串
    */
    private function flagName($flagIds = [])
    {
        if (empty($flagIds)) {
            return;
        }
        $flag_name = '';
        foreach ($flagIds as $v) {
            switch ($v) {
                case 1:
                    $flag_name .= '<span class="hui-font-style layui-badge" title="'.ContentFlagModel::FLAG[$v].'">'.mb_substr(ContentFlagModel::FLAG[$v],
                            0, 1, 'utf-8').'</span>';
                    break;
                case 2:
                    $flag_name .= '<span class="hui-font-style layui-badge layui-bg-orange" title="'.ContentFlagModel::FLAG[$v].'">'.mb_substr(ContentFlagModel::FLAG[$v],
                            0, 1, 'utf-8').'</span>';
                    break;
                case 3:
                    $flag_name .= '<span class="hui-font-style layui-badge layui-bg-green" title="'.ContentFlagModel::FLAG[$v].'">'.mb_substr(ContentFlagModel::FLAG[$v],
                            0, 1, 'utf-8').'</span>';
                    break;
                case 4:
                    $flag_name .= '<span class="hui-font-style layui-badge layui-bg-purple" title="'.ContentFlagModel::FLAG[$v].'">'.mb_substr(ContentFlagModel::FLAG[$v],
                            0, 1, 'utf-8').'</span>';
                    break;
                default:
                    $flag_name = "";
                    break;
            }
        }

        return $flag_name;

    }

    /**
     * 模型字段
     *
     * @param $model_id
     * @param $contentExt 模型字段对应数据
     */
    private function modelFields($model_id, $contentExt = [])
    {
        $data = ModelsFieldModel::getModelFields($model_id, $contentExt);

        return $data;
    }

}
